package com.hj.system.base.utils;

import com.hj.system.base.exception.CustomerRuntimeException;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.Properties;
import java.util.UUID;

public class FileUtil {
    static Logger logger = LoggerFactory.getLogger(FileUtil.class);

    public static void uploadFile(byte[] file, String filePath, String fileName) throws IOException {
        OutputStream out = null;
        try {
            if (mkdirFile(filePath)) {
                out = new FileOutputStream(new File(filePath + File.separator + fileName));
                out.write(file);
                out.flush();
                out.close();
            } else {
                throw new CustomerRuntimeException("文件路径创建错误");
            }
        } catch (RuntimeException e) {
            logger.info(e.getMessage());
        } finally {
            if (out != null) {
                out.close();
            }
        }

    }

    public static void uploadFile(InputStream inputStream, String filePath, String fileName) throws IOException {
        logger.info("文件路径：" + filePath + " 文件名称：" + fileName);
        if (mkdirFile(filePath)) {
            OutputStream out = new FileOutputStream(new File(filePath, fileName));
            IOUtils.copy(inputStream, out);
            out.close();
            inputStream.close();
        } else {
            throw new CustomerRuntimeException("文件路径创建错误");
        }
    }

    public static boolean mkdirFile(String filePath) {
        File targetFile = new File(filePath);
        if (!targetFile.exists()) {
            return targetFile.mkdirs();
        }
        return true;
    }



    public static String renameToUUID(String fileName) {
        return UUID.randomUUID() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
    }

    public static void readFile(OutputStream out, InputStream in) {
        try {
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = in.read(bytes)) != -1) {
                out.write(bytes, 0, len);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    out = null;
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    in = null;
                }
            }
        }
    }

    /**
     * 查看文件类型(防止参数中存在.点号或者其他特殊字符，所以先抽取文件名，然后再获取文件类型)
     * @param url
     * @return
     */
    public static String typeFromUrl(String url) {
        String nonPramStr = url.substring(0, url.indexOf("?") != -1 ? url.indexOf("?"): url.length());
        String fileName = nonPramStr.substring(nonPramStr.lastIndexOf("/") + 1);
        String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
        if (FileUtils.listPictureTypes().contains(fileType.toLowerCase())) {
            fileType = "picture";
        }
        if (FileUtils.listArchiveTypes().contains(fileType.toLowerCase())) {
            fileType = "compress";
        }
        if (FileUtils.listOfficeTypes().contains(fileType.toLowerCase())) {
            fileType = "office";
        }
        return fileType;
    }

    /**
     * 得到文件后缀
     * @param url
     * @return
     */
    public static String suffixFromUrl(String url) {
        String nonPramStr = url.substring(0, url.indexOf("?") != -1 ? url.indexOf("?"): url.length());
        String fileName = nonPramStr.substring(nonPramStr.lastIndexOf("/") + 1);
        String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
        return fileType;
    }

    /**
     * 从url中剥离出文件名
     * @param url
     * @return
     */
    public static String getFileNameFromURL(String url) {
        // 因为url的参数中可能会存在/的情况，所以直接url.lastIndexOf("/")会有问题
        // 所以先从？处将url截断，然后运用url.lastIndexOf("/")获取文件名
        String noQueryUrl = url.substring(0, url.indexOf("?") != -1 ? url.indexOf("?"): url.length());
        Properties props=System.getProperties(); //获得系统属性集
        String osName = props.getProperty("os.name"); //操作系统名称
        String fileName = noQueryUrl.substring(noQueryUrl.lastIndexOf("/") + 1);
        if(osName.contains("Window")) {
         fileName = noQueryUrl.substring(noQueryUrl.lastIndexOf("\\") + 1);
        }
        return fileName;
    }
}
